package org.NooLab.glue.components;

import java.util.SortedMap;
import java.util.TreeMap;

import org.NooLab.glue.MessageBoard;
import org.NooLab.glue.storage.MsgBoardDataStorage;
import org.NooLab.utilities.files.DFutils;
import org.NooLab.utilities.logging.PrintLog;




public class OpenTransactions {

	MessageBoardFactory mbf;
	
	MessageBoard mb = null;
	MsgBoardDataStorage storage;
	
	String filename="" ;
	
	// we use a "map" format: [Long]:[GUID], 
	SortedMap<Long,String> openTransactions = new TreeMap<Long,String>() ;
	
	PrintLog out = new PrintLog(2,true);
	DFutils fileutil = new DFutils();
	
	public OpenTransactions(MessageBoardFactory mbf){
		this.mbf = mbf;
		init();
	}
	
	public OpenTransactions( MessageBoardFactory mbf, String filename ){
		this.mbf = mbf;
		load(filename) ;
		this.filename = filename;
		init() ;
	}
	
	private void init(){
		
		mb = mbf.mb ;
		storage = mbf.participantsStorage ;
	}
	
	public void save(){
		if (filename.length()==0){
			return;
		}
		
		try{
			
			
			save(filename);
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void save(String filename){
		this.filename = filename;

		try{
			
			storage.storeTransactionDataObj( openTransactions, filename) ;
			
		}catch(Exception e){
			e.printStackTrace();
		}

	}

	public void load(){
		
		load( filename );
	}

	@SuppressWarnings("unchecked")
	public void load( String filename ){
		Object obj;
		
		
		try{
			if (fileutil.fileexists(filename)==false){
				
				return;
			}
			
			obj = storage.readTransactionDataObj(filename) ;
			openTransactions = (SortedMap<Long,String>)obj ;
			
		}catch(Exception e){
			
		}
	}
	
	public String createFilename( String name, long serialUID){
		String path, filname = "";
		
		path = storage.getHibernationPath("") ;
		 
		filname = "~otra-"+name+"-"+serialUID+".map" ;
		filname = fileutil.createPath( path, filname) ;
		
		
		filename = filname;
		
		return filname;
	}
	
	//public 

	public void addItem( long transactionID, String stringID ){
		openTransactions.put( transactionID, stringID) ;
	}
	
	public String getItem( long transactionID ){
		return getStringID( transactionID );
	}
	
	public String getStringID( long transactionID ){
		String pstr="";
		
		pstr = openTransactions.get( transactionID ) ;
		
		return pstr;
	}
	
	
	public void removeItem( long transactionID){
		openTransactions.remove(transactionID) ;
	}

	public boolean containsKey( long transactionID){
	
		return openTransactions.containsKey(transactionID);
	}
	
	
	public SortedMap<Long, String> getTransactions() {
		if (openTransactions==null){
			openTransactions = new TreeMap<Long,String>();
		}
		return openTransactions;
	}


	public void setTransactions(SortedMap<Long, String> openTransactions) {
		this.openTransactions = openTransactions;
	}
	

	
}
